package org.yx.service.smat.insert_material_sn_history;

import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.yx.exception.BizException;
import org.yx.models.SmatMsnDtl;
import org.yx.models.SmatMsnSts;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

import java.util.ArrayList;
import java.util.List;

/**
 * 增加物料批次履历，并返回新物料批次（此服务会主动增加一次履历序次）
 * 
 * @author zxw
 * @since 2018/05/20
 **/
public class SmatInsertMaterialSnHistoryService extends BaseService {
	public SmatInsertMaterialSnHistoryOut insertMaterialSnHistory(SmatInsertMaterialSnHistoryIn in) throws Exception {
		List<SmatMsnSts> stsList = new ArrayList<SmatMsnSts>();
		if (!CollUtil.isEmpty(in.getMsnStsList())) {
			for (SmatMsnSts msnSts : in.getMsnStsList()) {
				msnSts = selectOneLocked(SmatMsnSts.class, msnSts);
				if (msnSts == null) {
					throw new BizException("SMAT-0005", new FieldMap("msn", in.getMsn()));
				}
				stsList.add(msnSts);
			}
		}

		if (!StrUtil.isBlank(in.getMsn())) {
			SmatMsnSts msnSts = selectOneLocked(SmatMsnSts.class, in.getUserOrgCode(), in.getMsn());
			if (msnSts == null) {
				throw new BizException("SMAT-0005", new FieldMap("msn", in.getMsn()));
			}

			stsList.add(msnSts);
		}

		if (in.getMsnSts() != null) {
			SmatMsnSts sts = in.getMsnSts();
			sts.setOrgCode(in.getUserOrgCode());
			sts = selectOneLocked(sts);
			stsList.add(sts);
		}

		if (CollUtil.isEmpty(stsList)) {
			throw new BizException("SMAT-0004");
		}

		List<SmatMsnDtl> dtlList = new ArrayList<SmatMsnDtl>();
		for (SmatMsnSts msnSts : stsList) {
			if (msnSts.getDtlSeq() == null || msnSts.getDtlSeq().intValue() <= 0) {
				SmatMsnSts oldMsnSts = selectOne(SmatMsnSts.class, msnSts.getOrgCode(), msnSts.getMsn());
				if (oldMsnSts == null) {
					msnSts.setDtlSeq(1);
				} else {
					msnSts.setDtlSeq(msnSts.getDtlSeq() + 1);
				}
			}

			SmatMsnDtl dtl = new SmatMsnDtl();
			copyProperties(msnSts, dtl);
			dtl.setSeqNum(msnSts.getDtlSeq());

			dtlList.add(dtl);
		}

		updateBatch(stsList, "dtlSeq");
		insertBatch(dtlList);

		SmatInsertMaterialSnHistoryOut out = new SmatInsertMaterialSnHistoryOut();
		out.setMsnStsList(stsList);

		return out;
	}
}